console.log('Background script loaded')

// 确保后台脚本保持活跃
chrome.runtime.onInstalled.addListener(() => {
  console.log('Extension installed, background script is running')
})

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  console.log('Received message:', request)

  if (request.action === 'getPageContent') {
    console.log('Handling getPageContent request')

    // 确保返回true以保持消息通道开放
    const handleAsyncResponse = async () => {
      try {
        // 获取所有窗口信息
        const windows = await new Promise((resolve) => {
          chrome.windows.getAll({ populate: true }, resolve)
        })
        console.log('All windows:', windows)

        // 尝试从所有窗口中查找活动标签页
        for (const window of windows) {
          if (window.tabs && window.tabs.length > 0) {
            const activeTab = window.tabs.find((tab) => tab.active)
            if (activeTab && activeTab.id) {
              console.log(
                'Found active tab in window:',
                window.id,
                'Tab:',
                activeTab
              )

              // 执行脚本获取页面内容
              const results = await new Promise((resolve) => {
                chrome.scripting.executeScript(
                  {
                    target: { tabId: activeTab.id },
                    func: () => document.documentElement.outerHTML,
                  },
                  resolve
                )
              })

              if (results && results[0] && results[0].result) {
                return { content: results[0].result }
              }
            }
          }
        }

        // 如果所有查询方式都失败
        console.error('No suitable tab found after searching all windows')
        return { error: 'No active tab found' }
      } catch (error) {
        console.error('Error in background script:', error)
        return { error: error.message }
      }
    }

    // 处理异步响应
    handleAsyncResponse().then(sendResponse)

    // 返回true以保持消息通道开放
    return true
  }
})
